package com.cocoiko;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Calendar;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.app.AlertDialog.Builder;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.ToggleButton;

import com.cocoiko.client.ClientUtils;
import com.cocoiko.tools.facebook.FacebookUtils;
import com.cocoiko.tools.twitter.TwitterUtils;
import com.cocoiko.utils.CocoikoAccount;
import com.cocoiko.utils.CocoikoAccountStore;
import com.cocoiko.utils.CocoikoConstains;
import com.cocoiko.utils.CocoikoUtils;
import com.facebook.android.AsyncFacebookRunner.RequestListener;
import com.facebook.android.FacebookError;
import com.facebook.android.Util;

public class Setting extends Activity implements OnClickListener {

	private static final int BIRTHDAY_SELECT = 0;
	Button home_button;
	Button save_button;

	EditText name;
	TextView gender;
	TextView birthday;
	ImageView picture;
	EditText email;
	EditText pass;
	EditText pass_confirm;

	EditText introduce;

	ToggleButton twitter;
	ToggleButton facebook;

	ToggleButton lead_notive;
	ToggleButton follow_notive;

	ToggleButton lead_mail;
	ToggleButton follow_mail;

	TextView about;

	Button register_button;

	boolean isRegister;

	//
	CocoikoAccount account;
	Bitmap bitmap;

	ProgressDialog progress;

	// setting val

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.setting);

		// get view
		home_button = (Button) findViewById(R.id.home);
		save_button = (Button) findViewById(R.id.save);

		name = (EditText) findViewById(R.id.name);
		gender = (TextView) findViewById(R.id.gender);
		birthday = (TextView) findViewById(R.id.birthday);
		picture = (ImageView) findViewById(R.id.picture);
		email = (EditText) findViewById(R.id.email);
		pass = (EditText) findViewById(R.id.pass);
		pass_confirm = (EditText) findViewById(R.id.pass_confirm);

		introduce = (EditText) findViewById(R.id.introduce);

		twitter = (ToggleButton) findViewById(R.id.twitter_on);
		facebook = (ToggleButton) findViewById(R.id.facebook_on);

		lead_notive = (ToggleButton) findViewById(R.id.lead_notice);
		follow_notive = (ToggleButton) findViewById(R.id.follow_notive);

		lead_mail = (ToggleButton) findViewById(R.id.lead_mail);
		follow_mail = (ToggleButton) findViewById(R.id.follow_mail);

		about = (TextView) findViewById(R.id.about);

		register_button = (Button) findViewById(R.id.register);

		// set activity
		home_button.setOnClickListener(this);
		save_button.setOnClickListener(this);
		register_button.setOnClickListener(this);
		gender.setOnClickListener(this);
		birthday.setOnClickListener(this);

		// intent
		Bundle bundle = getIntent().getExtras();
		if (bundle != null) {
			// register
			isRegister = true;
			setRegisterView(isRegister);
			// facebook or twitter

			String account = bundle.getString("ACCOUNT");
			// progress = ProgressDialog.show(this,account,
			// "wait for a few minute ...");
			register(account);
		} else {
			// view setting
			isRegister = false;
			setRegisterView(isRegister);
			getSetting();
		}
		// register
		//test data
		birthday.setText("1989-08-05");
		email.setText("vannghia2avn@yahoo.com");
		pass.setText("nghia589");
		pass_confirm.setText("nghia589");
	}

	Handler handle = new Handler() {
		@Override
		public void handleMessage(android.os.Message msg) {
			// TODO Auto-generated method stub
			super.handleMessage(msg);
			showAccountInfo();
			// progress.dismiss();
		}
	};

	/**
	 * hidden home button and save button if activity is register va nguoc lai
	 * 
	 * @param register
	 */
	public void setRegisterView(boolean register) {

		if (register) {
			home_button.setVisibility(View.INVISIBLE);
			save_button.setVisibility(View.INVISIBLE);

			register_button.setText(R.string.REGISTER_JP);
		} else {
			home_button.setVisibility(View.VISIBLE);
			save_button.setVisibility(View.VISIBLE);

			register_button.setText(R.string.LOGOUT);
		}

	}

	/**
	 * 
	 * @return
	 */
	public boolean doUpdateSetting() {
		//
		getSettingInfo();
		CocoikoAccountStore.save(account, this);

		return true;
	}

	/**
	 * register and save setting
	 */
	public boolean doRegister() {
		// get info
		String message = getSettingInfo();
		if (message == null) {// correct input
			String status = ClientUtils.register(this, account);
			if (status == null) {
				//CocoikoAccountStore.save(account, this);
				return true;
			} else {
				new AlertDialog.Builder(this).setTitle("").setMessage(status)
						.setNeutralButton("Close", null).show();
			}
		}else{//incorrect input
			new AlertDialog.Builder(this).setTitle("").setMessage(message)
			.setNeutralButton("Close", null).show();
		}
		return false;
	}

	/**
	 * 
	 * @return
	 */
	public boolean doLogout() {
		return ClientUtils.logout(this);
	}

	/**
	 * register
	 * 
	 * @param account
	 */
	public void register(String account) {
		if (account != null) {
			if (account.equals(CocoikoConstains.FACEBOOK)) { // facebook
				getFacebookAccount();
			} else { // twitter
				getTwitterAccount();
			}
		}
	}

	/**
	 * 
	 */
	public void getSetting() {

		account = CocoikoAccountStore.restore(this);
		showAccountInfo();

	}

	/**
	 * 
	 * 
	 */
	public void getFacebookAccount() {

		// get facebook account info
		SharedPreferences share = getSharedPreferences(
				CocoikoConstains.FACEBOOK_SESSION, MODE_PRIVATE);
		FacebookUtils.getUserProfile(share, new FacebookUserProfileListener());

	}

	/**
	 * 
	 * @return null: no error String: error message
	 */
	public String getSettingInfo() {

		// name
		String inname = name.getText().toString();
		if (inname.equals(""))
			return "ニックネームを入力してください";
		account.setName(inname);

		// gender
		String ingender = gender.getText().toString();
		if (ingender.equals(""))
			return "性別を入力してください";
		account.setGender(ingender);

		// birthday
		String inbirthday = birthday.getText().toString();
		if (inbirthday.equals(""))
			return "誕生日を入力してください";
		account.setBirthday(inbirthday);

		// email
		String inemail = email.getText().toString();
		if (inemail.equals(""))
			return "メールを入力してください";
		account.setEmail(inemail);

		// password
		String password = pass.getText().toString();
		String password_confirm = pass_confirm.getText().toString();
		if (password.equals("") || password_confirm.equals("")) {
			return "パースワードを入力してください";
		}

		if (password.equals(password_confirm)) {
			account.setPassword(password);
		} else {// password error notice
			return "パースワードを再確認してください";
		}

		//
		account.setIntroduce(introduce.getText().toString());
		account.setOnTwitter(twitter.isChecked());
		account.setOnFacebook(facebook.isChecked());
		account.setLeadMail(lead_mail.isChecked());
		account.setLeadNotice(lead_notive.isChecked());
		account.setFollowMail(follow_mail.isChecked());
		account.setFollowNotice(follow_notive.isChecked());

		return null;

	}

	/**
	 * 
	 */
	public void showAccountInfo() {

		if (account != null) {

			name.setText(account.getName());
			if (account.getGender() != null
					&& account.getGender().equals("male")) {
				gender.setText(R.string.male_en);
			} else {
				gender.setText(R.string.female_en);
			}
			birthday.setText(account.getBirthday());
			picture.setImageBitmap(account.getAvatar());
			if (!account.getEmail().equals(""))
				email.setText(account.getEmail());
			introduce.setText(account.getIntroduce());

			twitter.setChecked(account.isOnTwitter());
			facebook.setChecked(account.isOnFacebook());
			lead_notive.setChecked(account.isLeadNotice());
			lead_mail.setChecked(account.isLeadMail());
			follow_notive.setChecked(account.isFollowNotice());
			follow_mail.setChecked(account.isFollowMail());

		}

	}

	/**
	 * 
	 * @return
	 */
	public boolean getTwitterAccount() {
		SharedPreferences prefs = getSharedPreferences(
				CocoikoConstains.SHARE_PREFER_NAME, MODE_PRIVATE);
		account = TwitterUtils.getTwitterUserProfile(prefs);
		account.setOnTwitter(true);
		showAccountInfo();
		// progress.dismiss();
		return false;
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// TODO Auto-generated method stub
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.menu, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// TODO Auto-generated method stub
		Intent intent;
		switch (item.getItemId()) {
		case R.id.home:
			if (!this.getClass().getName().equals(Home.class.getName())) {
				intent = new Intent(this, Home.class);
				startActivity(intent);
				finish();
			}
			break;
		case R.id.friends:
			if (!this.getClass().getName().equals(Friends.class.getName())) {
				intent = new Intent(this, Friends.class);
				startActivity(intent);
				finish();
			}
			break;
		case R.id.map:
			if (!this.getClass().getName().equals(Map.class.getName())) {
				intent = new Intent(this, Map.class);
				startActivity(intent);
				finish();
			}
			break;
		case R.id.allkokoiko:
			if (!this.getClass().getName().equals(AllCocoiko.class.getName())) {
				intent = new Intent(this, AllCocoiko.class);
				startActivity(intent);
				finish();
			}
			break;
		case R.id.message:
			if (!this.getClass().getName().equals(Message.class.getName())) {
				intent = new Intent(this, Message.class);
				startActivity(intent);
				finish();
			}
			break;
		case R.id.setting:
			if (!this.getClass().getName().equals(Setting.class.getName())) {
				finish();
				intent = new Intent(this, Setting.class);
				startActivity(intent);
				finish();
			}
			break;
		}
		return true;
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		if (v == home_button) {
			Intent intent = new Intent(this, Home.class);
			startActivity(intent);
			finish();
		}
		if (v == save_button) {
			boolean done = doUpdateSetting();
			if (done) {
				Intent intent = new Intent(this, Home.class);
				startActivity(intent);
				finish();
			}
		}
		if (v == register_button) {
			if (isRegister) {
				boolean done = doRegister();
				if (done) {
					Intent intent = new Intent(this, Home.class);
					startActivity(intent);
					finish();
				}
			} else {
				boolean done = doLogout();
				if (done) {
					finish();
				}else{
					
				}
			}
		}
		if (v == gender) {
			final String genders[] = { "male", "female" };
			Builder builder = new Builder(this);
			builder.setItems(genders, new DialogInterface.OnClickListener() {

				@Override
				public void onClick(DialogInterface dialog, int which) {
					// TODO Auto-generated method stub
					gender.setText(genders[which]);
					dialog.dismiss();
				}
			});
			AlertDialog alert = builder.create();
			alert.show();
		}
		if (v == birthday) {
			showDialog(BIRTHDAY_SELECT);
		}
	}

	@Override
	protected Dialog onCreateDialog(int id) {
		// TODO Auto-generated method stub
		// return super.onCreateDialog(id);

		Calendar cal = Calendar.getInstance();
		int year = cal.get(Calendar.YEAR);
		int month = cal.get(Calendar.MONTH);
		int day = cal.get(Calendar.DAY_OF_MONTH);

		switch (id) {
		case BIRTHDAY_SELECT:
			return new DatePickerDialog(this, dateListener, year, month, day);
		default:
			break;
		}
		return null;

	}

	private DatePickerDialog.OnDateSetListener dateListener = new DatePickerDialog.OnDateSetListener() {

		@Override
		public void onDateSet(DatePicker view, int year, int monthOfYear,
				int dayOfMonth) {
			// TODO Auto-generated method stub
			String date = year + "-" + monthOfYear + "-" + dayOfMonth;
			birthday.setText(date);
		}
	};

	public class FacebookUserProfileListener implements RequestListener {

		@Override
		public void onComplete(String response, Object state) {
			// TODO Auto-generated method stub
			try {

				Log.d("Facebook-User Request", "Response: " + response);

				final JSONObject json = Util.parseJson(response);

				String id = json.getString("id");

				account = new CocoikoAccount();
				account.setOnFacebook(true);
				account.setId(id);
				account.setName(json.getString("name"));
				account.setGender(json.getString("gender"));
				// picture
				try {
					URL url = new URL("http://graph.facebook.com/" + id
							+ "/picture");
					bitmap = CocoikoUtils.getBitmapFromUrl(url);
					account.setAvatar(bitmap);
				} catch (MalformedURLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

				// handler message
				handle.sendEmptyMessage(0);
			} catch (JSONException e) {
				Log.w("Facebook", "JSON Error in response");
			} catch (FacebookError e) {
				// TODO Auto-generated catch block
				Log.w("Facebook", e.toString());
			}

		}

		@Override
		public void onIOException(IOException e, Object state) {
			// TODO Auto-generated method stub

		}

		@Override
		public void onFileNotFoundException(FileNotFoundException e,
				Object state) {
			// TODO Auto-generated method stub

		}

		@Override
		public void onMalformedURLException(MalformedURLException e,
				Object state) {
			// TODO Auto-generated method stub

		}

		@Override
		public void onFacebookError(FacebookError e, Object state) {
			// TODO Auto-generated method stub

		}

	}
}
